/*
 * File:    CircularBuffer.c
 * Project:	HobbyPilotFirmware (HPF)
 * Author:  Wouter van Verre
 *
 * Created on February 12, 2011, 1:37 PM
 */

#include "Header.h"

void initCircularBuffer(CircularBuffer *buffer, int size)
{
    uint8 *pointer = calloc(size, sizeof(*pointer));

	buffer->size = size;
    buffer->numOfPlacesTaken = 0;

    buffer->startPointer = pointer;
    buffer->endPointer = &(pointer[size - 1]);
    buffer->readPointer = buffer->startPointer;
    buffer->writePointer = buffer->startPointer;
}

int8 writeToCircularBuffer(CircularBuffer *buffer, uint8 *data, int numOfBytes)
{
    if ((buffer->numOfPlacesTaken + numOfBytes) > buffer->size)
            return false;

    int i = 0;
	for (i = 0; i < numOfBytes; i++)
    {
        if (buffer->writePointer > buffer->endPointer)
            buffer->writePointer = buffer->startPointer;

        *(buffer->writePointer) = *(data + i);

        buffer->writePointer++;
		buffer->numOfPlacesTaken++;
    }
	
	return true;
}

int8 writeByteToCircularBuffer(CircularBuffer *buffer, uint8 data)
{
    if ((buffer->numOfPlacesTaken + 1) > buffer->size)
            return false;

    if (buffer->writePointer > buffer->endPointer)
    	buffer->writePointer = buffer->startPointer;

    *(buffer->writePointer) = data;

    buffer->writePointer++;
	buffer->numOfPlacesTaken++;

	return true;
}

int8 readByteFromCircularBuffer(CircularBuffer *buffer, uint8 *data)
{
    if (buffer->numOfPlacesTaken <= 0)
		return false;

	uint8 retVal;
	retVal = *(buffer->readPointer);
	*(buffer->readPointer) = 0;

	buffer->readPointer++;
	buffer->numOfPlacesTaken--;

	if (buffer->readPointer > buffer->endPointer)
		buffer->readPointer = buffer->startPointer;

	*data = retVal;
	return true;
}
